package com.qrpay.util;

import com.qrpay.model.BizException;
import com.qrpay.model.ErrorCode;
import com.qrpay.model.annotations.SignField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

/**
 * 加解密工具类
 */
public final class CryptoUtils {

    private static final Logger logger = LoggerFactory.getLogger(CryptoUtils.class);

    private CryptoUtils() {
    }

    public static String md5Hash(byte[] data) throws BizException {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(data);
            return new String(BytesUtils.toHex(md5.digest()));
        } catch (Exception e) {
            logger.error("md5Hash异常");
            throw new BizException(ErrorCode.SYSTEM_FAILED);
        }
    }

    /**
     * 签名
     *
     * @param request   用户上送请求（其中含有 @SignField 注解字段）
     * @param secretKey 用户密钥
     * @return
     */
    public static String sign(Object request, String secretKey) throws BizException {
        try {
            String content = getSortedString(request) + secretKey;
            return md5Hash(content.getBytes());
        } catch (Exception e) {
            logger.error("签名失败！", e);
            throw new BizException(ErrorCode.SIGN_ERROR);
        }
    }

    /**
     * 验签
     *
     * @param sign      待校验签名
     * @param request   待校验签名请求
     * @param secretKey 用户密钥
     * @return
     * @throws BizException
     */
    public static boolean verifySign(String sign, Object request, String secretKey) throws BizException {
        try {
            return sign(request, secretKey).equalsIgnoreCase(sign);
        } catch (Exception e) {
            logger.error("验签失败！", e);
            throw new BizException(ErrorCode.VERIFY_SIGN_ERROR);
        }
    }

    private static String getSortedString(Object o) {
        TreeMap<String, String> map = new TreeMap<String, String>();
        ObjectUtils.iterateAllFields(o.getClass(), (f) -> {
            SignField signField = f.getAnnotation(SignField.class);
            if (null != signField) {
                f.setAccessible(true);
                try {
                    if (null != f.get(o)) {
                        map.put(f.getName(), String.valueOf(f.get(o)));
                    }
                } catch (IllegalAccessException e) {
                    logger.warn("遍历Object字段时失败！Object={}, Field={}", o.getClass(), f.getName());
                }
            }
        });
        return getSortedStringForMap(map);
    }

    private static String getSortedStringForMap(TreeMap<String, String> model) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> e : model.entrySet()) {
            sb.append(e.getValue());
        }
        return sb.toString();
    }
}
